/**
 * 权限管理服务
 * 提供统一的权限检查、请求和管理功能
 */

class PermissionService {
  // 权限类型常量
  static PERMISSION_TYPES = {
    CLIPBOARD: 'clipboard',
    NOTIFICATION: 'notification',
    STORAGE: 'storage',
    SMS: 'sms',
    CAMERA: 'camera',
    LOCATION: 'location'
  };

  // 权限状态缓存
  static permissionCache = {};
  static cacheExpiry = 5000; // 缓存5秒

  /**
   * 检查单个权限状态
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>} 是否已授权
   */
  static async checkPermission(permissionType) {
    try {
      // 检查缓存
      const cached = this.getCachedPermission(permissionType);
      if (cached !== null) {
        return cached;
      }

      let granted = false;

      // #ifdef APP-PLUS
      granted = await this.checkPermissionApp(permissionType);
      // #endif

      // #ifdef H5
      granted = await this.checkPermissionH5(permissionType);
      // #endif

      // #ifdef MP
      granted = await this.checkPermissionMiniProgram(permissionType);
      // #endif

      // 缓存结果
      this.cachePermission(permissionType, granted);

      return granted;
    } catch (error) {
      console.error(`检查权限失败 [${permissionType}]:`, error);
      return false;
    }
  }

  /**
   * APP平台权限检查
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static checkPermissionApp(permissionType) {
    return new Promise((resolve) => {
      // #ifdef APP-PLUS
      if (typeof plus === 'undefined') {
        resolve(false);
        return;
      }

      const permissionMap = {
        clipboard: null, // 剪贴板不需要权限
        notification: 'NOTIFICATION',
        storage: 'WRITE_EXTERNAL_STORAGE',
        sms: 'READ_SMS',
        camera: 'CAMERA',
        location: 'ACCESS_FINE_LOCATION'
      };

      const androidPermission = permissionMap[permissionType];

      // 剪贴板权限在APP平台默认可用
      if (permissionType === 'clipboard') {
        resolve(true);
        return;
      }

      if (!androidPermission) {
        resolve(false);
        return;
      }

      // Android平台权限检查
      if (plus.os.name === 'Android') {
        try {
          const main = plus.android.runtimeMainActivity();
          const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
          const permissionName = 'android.permission.' + androidPermission;
          
          const status = main.checkSelfPermission(permissionName);
          const granted = status === PackageManager.PERMISSION_GRANTED;
          resolve(granted);
        } catch (error) {
          console.error('权限检查失败:', error);
          resolve(false);
        }
      } else {
        // iOS平台
        resolve(true); // iOS大部分权限在使用时请求
      }
      // #endif

      // #ifndef APP-PLUS
      resolve(false);
      // #endif
    });
  }

  /**
   * H5平台权限检查
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static async checkPermissionH5(permissionType) {
    // #ifdef H5
    if (permissionType === 'clipboard') {
      // H5剪贴板API需要用户交互
      return typeof navigator !== 'undefined' && 
             (navigator.clipboard !== undefined || document.queryCommandSupported('copy'));
    }

    if (permissionType === 'notification') {
      return typeof Notification !== 'undefined' && Notification.permission === 'granted';
    }

    // 其他权限H5不支持
    return false;
    // #endif

    // #ifndef H5
    return false;
    // #endif
  }

  /**
   * 小程序平台权限检查
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static async checkPermissionMiniProgram(permissionType) {
    return new Promise((resolve) => {
      // #ifdef MP
      const scopeMap = {
        clipboard: 'scope.clipboard',
        notification: 'scope.notification',
        camera: 'scope.camera',
        location: 'scope.userLocation'
      };

      const scope = scopeMap[permissionType];
      if (!scope) {
        resolve(false);
        return;
      }

      uni.getSetting({
        success: (res) => {
          resolve(res.authSetting[scope] === true);
        },
        fail: () => {
          resolve(false);
        }
      });
      // #endif

      // #ifndef MP
      resolve(false);
      // #endif
    });
  }

  /**
   * 请求权限授权
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>} 是否授权成功
   */
  static async requestPermission(permissionType) {
    try {
      // 清除缓存
      this.clearPermissionCache(permissionType);

      // #ifdef APP-PLUS
      return await this.requestPermissionApp(permissionType);
      // #endif

      // #ifdef H5
      return await this.requestPermissionH5(permissionType);
      // #endif

      // #ifdef MP
      return await this.requestPermissionMiniProgram(permissionType);
      // #endif

      return false;
    } catch (error) {
      console.error(`请求权限失败 [${permissionType}]:`, error);
      return false;
    }
  }

  /**
   * APP平台请求权限
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static requestPermissionApp(permissionType) {
    return new Promise((resolve) => {
      // #ifdef APP-PLUS
      if (typeof plus === 'undefined') {
        resolve(false);
        return;
      }

      const permissionMap = {
        notification: 'NOTIFICATION',
        storage: 'WRITE_EXTERNAL_STORAGE',
        sms: 'READ_SMS',
        camera: 'CAMERA',
        location: 'ACCESS_FINE_LOCATION'
      };

      const androidPermission = permissionMap[permissionType];

      if (!androidPermission) {
        resolve(false);
        return;
      }

      if (plus.os.name === 'Android') {
        plus.android.requestPermissions(
          [androidPermission],
          (result) => {
            const granted = result.granted && result.granted.length > 0;
            this.cachePermission(permissionType, granted);
            resolve(granted);
          },
          (error) => {
            console.error('请求权限失败:', error);
            resolve(false);
          }
        );
      } else {
        // iOS平台
        resolve(true);
      }
      // #endif

      // #ifndef APP-PLUS
      resolve(false);
      // #endif
    });
  }

  /**
   * H5平台请求权限
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static async requestPermissionH5(permissionType) {
    // #ifdef H5
    if (permissionType === 'notification') {
      if (typeof Notification !== 'undefined') {
        const permission = await Notification.requestPermission();
        return permission === 'granted';
      }
    }
    return false;
    // #endif

    // #ifndef H5
    return false;
    // #endif
  }

  /**
   * 小程序平台请求权限
   * @param {string} permissionType - 权限类型
   * @returns {Promise<boolean>}
   */
  static requestPermissionMiniProgram(permissionType) {
    return new Promise((resolve) => {
      // #ifdef MP
      const scopeMap = {
        camera: 'scope.camera',
        location: 'scope.userLocation'
      };

      const scope = scopeMap[permissionType];
      if (!scope) {
        resolve(false);
        return;
      }

      uni.authorize({
        scope: scope,
        success: () => {
          this.cachePermission(permissionType, true);
          resolve(true);
        },
        fail: () => {
          resolve(false);
        }
      });
      // #endif

      // #ifndef MP
      resolve(false);
      // #endif
    });
  }

  /**
   * 打开系统权限设置页面
   * @param {string} permissionType - 权限类型（可选，用于特定权限设置）
   */
  static openSystemSettings(permissionType = null) {
    try {
      // #ifdef APP-PLUS
      if (typeof plus !== 'undefined') {
        if (plus.os.name === 'Android') {
          // Android打开应用设置页面
          const Intent = plus.android.importClass('android.content.Intent');
          const Settings = plus.android.importClass('android.provider.Settings');
          const Uri = plus.android.importClass('android.net.Uri');
          const mainActivity = plus.android.runtimeMainActivity();
          
          const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
          const uri = Uri.fromParts('package', mainActivity.getPackageName(), null);
          intent.setData(uri);
          mainActivity.startActivity(intent);
        } else if (plus.os.name === 'iOS') {
          // iOS打开应用设置页面
          const UIApplication = plus.ios.importClass('UIApplication');
          const application = UIApplication.sharedApplication();
          const NSURL = plus.ios.importClass('NSURL');
          const setting = NSURL.URLWithString('app-settings:');
          application.openURL(setting);
        }
      }
      // #endif

      // #ifdef H5
      uni.showModal({
        title: '权限设置',
        content: '请在浏览器设置中允许相关权限',
        showCancel: false
      });
      // #endif

      // #ifdef MP
      uni.openSetting({
        success: (res) => {
          console.log('打开设置成功:', res);
        },
        fail: (error) => {
          console.error('打开设置失败:', error);
        }
      });
      // #endif
    } catch (error) {
      console.error('打开系统设置失败:', error);
      uni.showToast({
        title: '无法打开设置',
        icon: 'none'
      });
    }
  }

  /**
   * 获取所有权限状态
   * @returns {Promise<Array>} 权限状态列表
   */
  static async getAllPermissionsStatus() {
    const permissions = [
      {
        id: this.PERMISSION_TYPES.CLIPBOARD,
        name: '剪贴板',
        description: '用于自动识别快递单号',
        icon: '📋',
        required: false
      },
      {
        id: this.PERMISSION_TYPES.NOTIFICATION,
        name: '通知',
        description: '用于包裹状态更新提醒',
        icon: '🔔',
        required: false
      },
      {
        id: this.PERMISSION_TYPES.STORAGE,
        name: '存储',
        description: '用于保存包裹数据',
        icon: '💾',
        required: true
      }
    ];

    // #ifdef APP-PLUS
    // Android平台添加短信权限
    if (typeof plus !== 'undefined' && plus.os.name === 'Android') {
      permissions.push({
        id: this.PERMISSION_TYPES.SMS,
        name: '短信',
        description: '用于自动识别短信中的快递信息（可选）',
        icon: '💬',
        required: false
      });
    }
    // #endif

    // 检查每个权限的状态
    const permissionsWithStatus = await Promise.all(
      permissions.map(async (permission) => {
        const granted = await this.checkPermission(permission.id);
        return {
          ...permission,
          granted
        };
      })
    );

    return permissionsWithStatus;
  }

  /**
   * 缓存权限状态
   * @param {string} permissionType - 权限类型
   * @param {boolean} granted - 是否已授权
   */
  static cachePermission(permissionType, granted) {
    this.permissionCache[permissionType] = {
      granted,
      timestamp: Date.now()
    };
  }

  /**
   * 获取缓存的权限状态
   * @param {string} permissionType - 权限类型
   * @returns {boolean|null} 权限状态，null表示缓存不存在或已过期
   */
  static getCachedPermission(permissionType) {
    const cached = this.permissionCache[permissionType];
    if (!cached) return null;

    const now = Date.now();
    if (now - cached.timestamp > this.cacheExpiry) {
      delete this.permissionCache[permissionType];
      return null;
    }

    return cached.granted;
  }

  /**
   * 清除权限缓存
   * @param {string} permissionType - 权限类型，不传则清除所有
   */
  static clearPermissionCache(permissionType = null) {
    if (permissionType) {
      delete this.permissionCache[permissionType];
    } else {
      this.permissionCache = {};
    }
  }
}

export default PermissionService;
